# -*- coding: utf-8 -*-
# 序列化、JSON

import pickle
import json

d = dict(name = 'Bob',age = 20,score = 80)
print(pickle.dumps(d))

with open('test.txt','wb') as f:
	pickle.dump(d,f)

with open('test.txt','rb') as f:
	d = pickle.load(f)
	print(d)


print(json.dumps(d))
json_str = '{"name": "Bob", "age": 20, "score": 80}'
print(json.loads(json_str))

class Student(object):
	def __init__(self,name,age,score):
		self.name = name
		self.age = age
		self.score = score

def student2dict(std):
	return {
		'name':std.name,
		'age':std.age,
		'score':std.score
	}
s = Student('Bob',20,88)
print(json.dumps(s,default=student2dict))
print(json.dumps(s,default=lambda obj:obj.__dict__))

def dict2student(d):
	return Student(d['name'],d['age'],d['score'])

json_str = '{"name": "Bob", "age": 20, "score": 88}'
print(json.loads(json_str,object_hook=dict2student))


# 对中文进行JSON序列化时，json.dumps()提供了一个ensure_ascii参数
obj = dict(name='小明',age=20)
s = json.dumps(obj,ensure_ascii=True)
print(s)